﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using YzApi.Models.Captcha;
using YzApi.Toolkit;

namespace YzApi.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class CaptchaController : BaseController
    {
        private const string key = "captcha";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public CaptchaController(DbContext context):base(context)
        {
        }

        /// <summary>
        /// 获取图形验证码（Captcha）的图片
        /// </summary>
        /// <remarks>
        /// 后台会自动将其文本保存在session中
        /// </remarks>
        /// <returns>？TODO：这里的注释UISwagger中显示不出来？图形验证码（Captcha）的图片</returns>
        [HttpGet]
        public FileResult Get()
        {
            string text = Captcha.CreateText();
            ISession session = HttpContext.Session;
            session.SetString(key, text);
            return File(Captcha.CreateGraphic(text), @"image/jpeg");
        }

        /// <summary>
        /// 验证用户是否输入正确的Captcha值。
        /// </summary>
        /// <remarks>
        /// 验证过后，无论正确与否，后端都会销毁原captcha
        /// </remarks>
        /// <param name="text">用户输入的Captcha值</param>
        /// <returns>ValidateResult</returns>
        [HttpPost]
        public ValidateResult Validate(string text)
        {
            ISession session = HttpContext.Session;
            ValidateResult result = new ValidateResult();
            string stored = session.GetString(key);
            
            if (string.IsNullOrEmpty(stored))
            {
                result.Error = "* 验证码已过期";
                return result;
            }

            result.Correct = text == session.GetString(key);
            if (!result.Correct)
            {
                result.Error = "* 验证码错误";
            }
            session.Remove(key);

            return result;
        }
    }
}